package com.itheima.bakery.demos.web.controller;


import com.itheima.bakery.demos.web.model.Order;
import com.itheima.bakery.demos.web.model.OrderDetail;
import com.itheima.bakery.demos.web.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.http.ResponseEntity;
import com.itheima.bakery.demos.web.Repositories.OrderRepository;
import org.springframework.http.HttpStatus;
import com.itheima.bakery.demos.web.model.ShippingAddress;
@RestController
@RequestMapping("/api/orders")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderRepository orderRepository;

    @GetMapping
    public List<Order> listOrders() {
        return orderService.findAllOrders();
    }

    @PostMapping
    public Order createOrder(@RequestBody Order order) {
        return orderService.saveOrder(order);
    }

    @GetMapping("/{id}")
    public Order getOrderById(@PathVariable Integer id) {
        return orderService.findOrderById(id).orElse(null);
    }

    @PutMapping("/{id}")
    public Order updateOrder(@PathVariable Integer id, @RequestBody Order order) {
        order.setOrderID(id);
        return orderService.saveOrder(order);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteOrder(@PathVariable Integer id) {
        boolean success = orderService.deleteOrder(id);
        if (success) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "Order deleted successfully");
            response.put("orderId", id);
            return ResponseEntity.ok(response);
        } else {
            Map<String, Object> response = new HashMap<>();
            response.put("error", "Order not found");
            response.put("orderId", id);
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/update-total")
    public ResponseEntity<?> updateOrderTotal(@RequestParam Integer orderId, @RequestParam BigDecimal totalAmount) {
        try {
            // 检查订单是否存在
            Order order = orderRepository.findById(orderId)
                    .orElseThrow(() -> new RuntimeException("Order not found with ID: " + orderId));

            // 更新订单总金额
            order.setTotalAmount(totalAmount);
            orderRepository.save(order);

            return ResponseEntity.ok("Order total amount updated successfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error updating order total amount");
        }
    }
    @GetMapping("/{id}/details")
    public List<OrderDetail> getOrderDetailsByOrderId(@PathVariable Integer id) {
        return orderService.findOrderDetailsByOrderId(id);
    }
    @PutMapping("/update-address")
    public ResponseEntity<Order> updateOrderAddress(@RequestParam("orderid") Integer orderid, @RequestParam("addressId") Integer addressId) {
        try {
            Order updatedOrder = orderService.updateOrderAddress(orderid, addressId);
            return ResponseEntity.ok(updatedOrder);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }
    @GetMapping("/{id}/address")
    public ResponseEntity<ShippingAddress> getShippingAddressByOrderID(@PathVariable Integer id) {
        return orderService.getShippingAddressByOrderID(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }
}